package com.green.service.manage.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.green.common.page.Pagination;
import com.green.dao.manage.ErpPackageDao;
import com.green.model.manage.ErpPackage;
import com.green.model.manage.PrivilegeRule;
import com.green.model.manage.enums.StateEnum;
import com.green.service.common.ServiceContext;
import com.green.service.common.impl.BaseServiceImpl;
import com.green.service.manage.ErpPackageService;
import com.green.service.manage.PrivilegeRuleService;



/**
 * 
 * 
 */
@Transactional
@Repository("erpPackageService")
public class ErpPackageServiceImpl extends BaseServiceImpl implements ErpPackageService {
	@Autowired
	private ErpPackageDao erpPackageDao;
	@Autowired
	private PrivilegeRuleService privilegeRuleService;
	@Override
	public int insertErpPackage(ErpPackage ct) {
		
		Map<String, Object> param = new HashMap<String, Object>();	
		param.put("positionId", ct.getPositionId());
		param.put("limitCity", ct.getLimitCity());
		param.put("joinType", ct.getType());
		param.put("status", StateEnum.EFFICTIVE);
		List<ErpPackage> list=erpPackageDao.getErpPackageList(param);
		if(null==list||list.size()<=0){
		String dotJsonKun = ct.getDotJsonDetail();
		JSONArray array = JSONArray.fromObject(dotJsonKun);
		for (int i = 0; i < array.size(); i++) {
			JSONObject obj = array.getJSONObject(i);
			PrivilegeRule privilegeRule=new PrivilegeRule();
			privilegeRule.setCreateBy(ServiceContext.getLoginPerson());
			privilegeRule.setId(UUID.randomUUID().toString());
			privilegeRule.setErpPackage(ct);
			privilegeRule.setName(obj.getString("name"));
			privilegeRule.setMonth(obj.getInt("month"));
			privilegeRule.setDiscount(obj.getString("discount"));
			privilegeRuleService.insertPrivilegeRule(privilegeRule);
			}
		return erpPackageDao.insertErpPackage(ct);
		}else{
		return 2;
		}
	}

	@Override
	public int updateErpPackage(ErpPackage ct) {
		return erpPackageDao.updateErpPackage(ct);
	}

	@Override
	public int deleteErpPackage(Map<String, Object> param) {
		return erpPackageDao.deleteErpPackage(param);
	}

	@Override
	public ErpPackage getErpPackageById(String id) {
		return erpPackageDao.getErpPackageById(id);
	}

	@Override
	public List<ErpPackage> getErpPackageList(Map<String, Object> param) {
		return erpPackageDao.getErpPackageList(param);
	}

	@Override
	public Pagination<ErpPackage> getErpPackagePagination(
			Pagination<ErpPackage> pag, Map<String, Object> param) {
		return erpPackageDao.getErpPackagePagination(pag, param);
	}
	
	
}
